package com.example.shop.common.configs;

import com.example.shop.common.utils.Constants;
import com.example.shop.common.utils.RedisService;
import com.example.shop.domain.sys.SysDict;
import com.example.shop.sys.dict.service.SysDictService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 缓存字典信息
 *
 * @author hcj
 */
@Component
@Order(2)
public class CacheConfig implements ApplicationRunner {

    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${system.crawler.ips}")
    private String ips;

    private static final Logger logger = LoggerFactory.getLogger(CacheConfig.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<SysDict> list = sysDictService.findList(new SysDict());
        redisService.set("dist", list);

        if(StringUtils.isNotBlank(ips)){
            // 缓存代理IP
            ListOperations operation = redisTemplate.opsForList();

            String[] strings = ips.split(",");

            Map<String, Object> map = null;
            for (String s : strings) {
                map = new HashMap<>();
                String[] ip = s.split(":");
                map.put("ip",ip[0]);
                map.put("port",ip[1]);
                operation.leftPush(Constants.IP_QUEUE, map);
            }
        }

        logger.info("缓存初始化完成！");
    }
}
